// 全局变量
let token = localStorage.getItem('token');
let userEmail = localStorage.getItem('userEmail') || '';
let progressChart = null;
let currentCompleteHabitId = null;
let currentViewHabitId = null;
let currentPage = 1;
let totalPages = 1;

// 刷新验证码
function refreshCaptcha() {
    const captchaImage = document.getElementById('captchaImage');
    if (captchaImage) {
        captchaImage.src = `/api/auth/captcha?t=${new Date().getTime()}`;
    }
}

// 显示验证码字段
function showVerificationCodeField() {
    const formContainer = document.querySelector('#authForm .space-y-4');
    
    // 如果验证码字段已经存在，直接返回
    if (document.getElementById('verificationCode')) {
        return;
    }
    
    // 创建验证码容器
    const verificationContainer = document.createElement('div');
    verificationContainer.className = 'mt-4';
    
    // 验证码UI
    verificationContainer.innerHTML = `
        <div class="flex items-center space-x-2 mb-2">
            <input type="text" id="verificationCode" placeholder="验证码" class="flex-1 px-4 py-2 border rounded-lg">
            <img id="captchaImage" class="h-10 cursor-pointer" alt="验证码" onclick="refreshCaptcha()">
        </div>
        <p id="captchaError" class="text-red-500 text-sm hidden">验证码错误，请重新输入</p>
    `;
    
    // 将验证码添加到密码输入框后面
    const passwordInput = document.getElementById('password');
    passwordInput.parentNode.insertBefore(verificationContainer, passwordInput.nextSibling);
    
    // 加载验证码图片
    refreshCaptcha();
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    token = localStorage.getItem('token');
    if (token) {
        showMainApp();
        loadUserData();
        setupIconButtons();
        
        // 添加用户头像点击事件
        document.getElementById('userInfo').addEventListener('click', showUserCenter);
        
        // 初始化习惯Tab切换
        initHabitTabs();
    } else {
        showAuthForm();
    }
});

// 初始化习惯Tab切换
function initHabitTabs() {
    const activeHabitsTab = document.getElementById('activeHabitsTab');
    const completedHabitsTab = document.getElementById('completedHabitsTab');
    const habitsContainer = document.getElementById('habitsContainer');
    const completedHabitsContainer = document.getElementById('completedHabitsContainer');
    
    if (activeHabitsTab && completedHabitsTab) {
        activeHabitsTab.addEventListener('click', function() {
            // 更新tab样式
            activeHabitsTab.classList.add('text-green-600', 'border-green-500');
            activeHabitsTab.classList.remove('text-gray-500', 'border-transparent');
            completedHabitsTab.classList.add('text-gray-500', 'border-transparent');
            completedHabitsTab.classList.remove('text-green-600', 'border-green-500');
            
            // 显示/隐藏内容
            habitsContainer.classList.remove('hidden');
            completedHabitsContainer.classList.add('hidden');
        });
        
        completedHabitsTab.addEventListener('click', function() {
            // 更新tab样式
            completedHabitsTab.classList.add('text-green-600', 'border-green-500');
            completedHabitsTab.classList.remove('text-gray-500', 'border-transparent');
            activeHabitsTab.classList.add('text-gray-500', 'border-transparent');
            activeHabitsTab.classList.remove('text-green-600', 'border-green-500');
            
            // 显示/隐藏内容
            habitsContainer.classList.add('hidden');
            completedHabitsContainer.classList.remove('hidden');
            
            // 加载已完成习惯
            loadCompletedHabits(1);
        });
    }
}

// 显示/隐藏界面
function showAuthForm() {
    document.getElementById('authForm').style.display = 'flex';
    document.getElementById('mainApp').style.display = 'none';
    
    // 清空验证码字段
    const verificationField = document.querySelector('#authForm .space-y-4.mt-4');
    if (verificationField) {
        verificationField.remove();
    }
    
    // 清空输入框
    document.getElementById('email').value = '';
    document.getElementById('password').value = '';
    
    // 显示验证码字段（在页面加载时就显示验证码）
    showVerificationCodeField();
    refreshCaptcha();
}

function showMainApp() {
    document.getElementById('authForm').style.display = 'none';
    document.getElementById('mainApp').style.display = 'block';
    
    // 显示用户信息
    userEmail = localStorage.getItem('userEmail') || '';
    if (userEmail) {
        const initial = userEmail.charAt(0).toUpperCase();
        document.getElementById('userInitial').textContent = initial;
        document.getElementById('userEmail').textContent = userEmail;
        document.getElementById('welcomeName').textContent = userEmail.split('@')[0];
    }
}

// 认证相关函数
async function login() {
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const verificationCode = document.getElementById('verificationCode') ? document.getElementById('verificationCode').value : '';
    
    if (!email || !password) {
        showToast('错误', '请填写邮箱和密码');
        return;
    }
    
    if (!verificationCode) {
        showToast('错误', '请填写验证码');
        // 显示验证码错误提示
        const captchaError = document.getElementById('captchaError');
        if (captchaError) {
            captchaError.textContent = '请填写验证码';
            captchaError.classList.remove('hidden');
        }
        return;
    }
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email, password, verificationCode }),
        });
        
        const data = await response.json();
        
        if (response.ok) {
            token = data.token;
            userEmail = email;
            localStorage.setItem('token', token);
            localStorage.setItem('userEmail', email);
            showMainApp();
            loadUserData();
            loadRecommendations();
        } else {
            // 刷新验证码
            refreshCaptcha();
            
            // 显示验证码错误提示
            if (data.error && data.error.includes('验证码')) {
                const captchaError = document.getElementById('captchaError');
                if (captchaError) {
                    captchaError.textContent = data.error;
                    captchaError.classList.remove('hidden');
                }
            } else {
                showToast('登录失败', data.error || '用户名或密码错误');
            }
        }
    } catch (error) {
        console.error('登录错误:', error);
        showToast('错误', '登录过程中发生错误');
    }
}

async function register() {
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const verificationCode = document.getElementById('verificationCode') ? document.getElementById('verificationCode').value : '';
    
    if (!email || !password) {
        showToast('错误', '请填写邮箱和密码');
        return;
    }
    
    if (password.length < 6) {
        showToast('错误', '密码长度至少为6位');
        return;
    }
    
    try {
        // 如果未显示验证码字段，先发送获取验证码请求
        if (!document.getElementById('verificationCode')) {
            showVerificationCodeField();
            await getVerificationCode(email);
            return; // 等待用户输入验证码后再次点击注册
        }
        
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email, password, verificationCode }),
        });
        
        const data = await response.json();
        
        if (response.ok) {
            localStorage.setItem('token', data.token);
            localStorage.setItem('userEmail', email);
            showMainApp();
            loadUserData();
            showToast('注册成功', '欢迎加入BeHabit');
        } else {
            showToast('注册失败', data.error || '注册失败，请稍后重试');
            // 刷新验证码
            if (data.requiresVerification) {
                await getVerificationCode(email);
            }
        }
    } catch (error) {
        console.error('注册错误:', error);
        showToast('错误', '注册过程中发生错误');
    }
}

function logout() {
    token = null;
    userEmail = '';
    localStorage.removeItem('token');
    localStorage.removeItem('userEmail');
    showAuthForm();
}

// 习惯管理
async function loadUserData() {
    try {
        // 加载分页习惯列表
        await loadHabitsPage(currentPage);
        
        // 加载统计数据
        const statsResponse = await fetch('/api/habits/stats', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (statsResponse.ok) {
            const stats = await statsResponse.json();
            updateStats(stats);
            renderBadges(stats.badges);
        }
        
        // 加载图表数据
        const chartResponse = await fetch('/api/habits/chart', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (chartResponse.ok) {
            const chartData = await chartResponse.json();
            initProgressChart(chartData);
        }
        
        // 加载推荐数据
        await loadRecommendations();
        
        // 加载文章
        await loadArticles();
    } catch (error) {
        console.error('加载数据错误:', error);
    }
}

// 全局请求拦截函数
async function fetchWithAuth(url, options = {}) {
    // 确保每次请求都获取最新的token
    token = localStorage.getItem('token');
    
    // 如果有令牌，添加到请求头
    if (token) {
        options.headers = {
            ...options.headers,
            'Authorization': `Bearer ${token}`
        };
    }
    
    try {
        const response = await fetch(url, options);
        
        // 如果返回401或403，可能是令牌问题
        if (response.status === 401 || response.status === 403) {
            console.log('可能的授权问题，检查响应');
            try {
                const errorData = await response.json();
                if (errorData.error === '无效的令牌') {
                    console.log('令牌已过期，重定向到登录页面');
                    // 清除令牌
                    localStorage.removeItem('token');
                    localStorage.removeItem('userEmail');
                    // 显示登录页面
                    showAuthForm();
                    return { error: '会话已过期，请重新登录' };
                }
                return { response, error: errorData.error };
            } catch (e) {
                return { response, error: '授权错误' };
            }
        }
        
        // 尝试解析JSON
        try {
            const data = await response.json();
            return { response, data };
        } catch (e) {
            return { response, data: null };
        }
    } catch (error) {
        console.error('请求错误:', error);
        return { error: '网络请求失败' };
    }
}

// 加载分页习惯数据
async function loadHabitsPage(page) {
    try {
        const { response, data, error } = await fetchWithAuth(`/api/habits/page/${page}`);
        
        if (error) {
            console.error(error);
            return;
        }

        if (response && response.ok) {
            renderHabits(data.habits);
            
            // 更新分页控件
            if (data.pagination.total > data.pagination.pageSize) {
                updatePagination(data.pagination);
                document.getElementById('paginationControls').classList.remove('hidden');
            } else {
                document.getElementById('paginationControls').classList.add('hidden');
            }
        }
    } catch (error) {
        console.error('加载习惯分页错误:', error);
    }
}

// 更新分页控件
function updatePagination(pagination) {
    currentPage = pagination.page;
    totalPages = pagination.totalPages;
    
    const pageStart = ((pagination.page - 1) * pagination.pageSize) + 1;
    const pageEnd = Math.min(pagination.page * pagination.pageSize, pagination.total);
    
    document.getElementById('pageStart').textContent = pageStart;
    document.getElementById('pageEnd').textContent = pageEnd;
    document.getElementById('totalItems').textContent = pagination.total;
    document.getElementById('currentPage').textContent = pagination.page;
    
    // 上一页按钮
    const prevBtn = document.getElementById('prevPageBtn');
    if (pagination.page <= 1) {
        prevBtn.disabled = true;
        prevBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        prevBtn.disabled = false;
        prevBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        prevBtn.onclick = () => loadHabitsPage(pagination.page - 1);
    }
    
    // 下一页按钮
    const nextBtn = document.getElementById('nextPageBtn');
    if (pagination.page >= pagination.totalPages) {
        nextBtn.disabled = true;
        nextBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        nextBtn.disabled = false;
        nextBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        nextBtn.onclick = () => loadHabitsPage(pagination.page + 1);
    }
}

// 加载推荐习惯
async function loadRecommendations() {
    try {
        const container = document.getElementById('recommendationsContainer');
        container.innerHTML = '<div class="text-center text-gray-500 py-2"><i class="fas fa-spinner fa-spin mr-2"></i> 加载推荐中...</div>';
        
        const response = await fetch('/api/habits/recommendations', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const recommendations = await response.json();
            renderRecommendations(recommendations);
        }
    } catch (error) {
        console.error('加载推荐错误:', error);
        const container = document.getElementById('recommendationsContainer');
        container.innerHTML = '<p class="text-gray-500 text-center py-2">暂无推荐，请稍后再试</p>';
    }
}

// 渲染推荐习惯
function renderRecommendations(recommendations) {
    const container = document.getElementById('recommendationsContainer');
    container.innerHTML = '';
    
    if (!recommendations || recommendations.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-2">已经把全部好习惯推荐给你啦</p>';
        return;
    }
    
    recommendations.slice(0, 3).forEach(rec => {
        const item = document.createElement('div');
        item.className = 'flex items-start space-x-3 p-2 hover:bg-gray-50 rounded cursor-pointer';
        item.onclick = () => applyRecommendation(rec.id);
        
        item.innerHTML = `
            <div class="h-8 w-8 rounded-full bg-${rec.color}-100 flex-shrink-0 flex items-center justify-center mt-1">
                <i class="fas fa-${rec.icon} text-${rec.color}-500 text-xs"></i>
            </div>
            <div>
                <p class="text-sm font-medium">${rec.title}</p>
                <p class="text-xs text-gray-500">${rec.description}</p>
            </div>
        `;
        container.appendChild(item);
    });
    
    // 添加更多链接
    if (recommendations.length > 3) {
        const moreLink = document.createElement('div');
        moreLink.className = 'text-center mt-2';
        moreLink.innerHTML = `<button class="text-sm text-blue-500 hover:text-blue-700">查看更多推荐 (${recommendations.length})</button>`;
        moreLink.onclick = showAllRecommendations;
        container.appendChild(moreLink);
    }
}

// 显示所有推荐
function showAllRecommendations() {
    // 这里可以实现显示所有推荐的弹窗
    alert('此功能正在开发中，敬请期待！');
}

// 应用推荐的习惯
async function applyRecommendation(id) {
    try {
        const response = await fetch(`/api/habits/apply-recommendation/${id}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            showToast('习惯已添加！', '从今天开始培养这个好习惯吧！');
            loadUserData();
        }
    } catch (error) {
        console.error('应用推荐习惯错误:', error);
    }
}

// 渲染习惯
function renderHabits(habits) {
    const container = document.getElementById('habitsContainer');
    container.innerHTML = '';

    if (habits.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-8">你还没有添加任何习惯，点击上方的"添加习惯"按钮开始吧！</p>';
        return;
    }

    habits.forEach(habit => {
        const card = document.createElement('div');
        card.className = 'habit-card bg-white border border-gray-200 rounded-lg p-4';
        card.dataset.habitId = habit.id;
        
        // 添加长按事件
        let pressTimer;
        card.addEventListener('mousedown', function() {
            pressTimer = window.setTimeout(function() {
                showDeleteConfirm(habit.id, habit.title);
            }, 800); // 800ms的长按时间
        });
        
        card.addEventListener('mouseup', function() {
            clearTimeout(pressTimer);
        });
        
        card.addEventListener('mouseleave', function() {
            clearTimeout(pressTimer);
        });
        
        // 添加触摸事件支持（移动设备）
        card.addEventListener('touchstart', function(e) {
            pressTimer = window.setTimeout(function() {
                showDeleteConfirm(habit.id, habit.title);
            }, 800);
        });
        
        card.addEventListener('touchend', function() {
            clearTimeout(pressTimer);
        });
        
        card.addEventListener('touchmove', function() {
            clearTimeout(pressTimer);
        });
        
        // 获取图标和颜色
        const iconInfo = getIconInfo(habit);
        
        card.innerHTML = `
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3 cursor-pointer" onclick="viewHabitDetails(${habit.id})">
                    <div class="h-10 w-10 rounded-full bg-${iconInfo.color}-100 flex items-center justify-center">
                        <i class="fas fa-${iconInfo.icon} text-${iconInfo.color}-500"></i>
                    </div>
                    <div>
                        <h3 class="font-medium">${habit.title}</h3>
                        <p class="text-xs text-gray-500">${getTriggerText(habit)}</p>
                    </div>
                </div>
                <button onclick="showCompleteModal(${habit.id}, '${habit.title}')" class="habit-complete-btn bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-sm flex items-center">
                    标记完成
                </button>
            </div>
        `;
        container.appendChild(card);
    });
}

// 查看习惯详情
async function viewHabitDetails(habitId) {
    currentViewHabitId = habitId;
    
    try {
        const response = await fetch(`/api/habits/${habitId}/completions`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            showHabitDetailsModal(data.habit, data.completions);
        }
    } catch (error) {
        console.error('获取习惯详情错误:', error);
    }
}

// 显示习惯详情模态框
function showHabitDetailsModal(habit, completions) {
    const iconInfo = getIconInfo(habit);
    
    // 设置标题和信息
    document.getElementById('habitDetailsTitle').textContent = habit.title;
    document.getElementById('habitDetailsTrigger').textContent = getTriggerText(habit);
    
    // 设置难度
    let difficultyText = '';
    for (let i = 0; i < habit.difficulty; i++) {
        difficultyText += '⭐';
    }
    document.getElementById('habitDetailsDifficulty').textContent = difficultyText;
    
    // 设置图标
    const iconElement = document.getElementById('habitDetailsIcon');
    iconElement.className = `h-10 w-10 rounded-full bg-${iconInfo.color}-100 flex items-center justify-center mr-3`;
    iconElement.querySelector('i').className = `fas fa-${iconInfo.icon} text-${iconInfo.color}-500`;
    
    // 渲染完成记录
    const completionsList = document.getElementById('habitCompletionsList');
    completionsList.innerHTML = '';
    
    if (completions.length === 0) {
        completionsList.innerHTML = '<p class="text-gray-500 text-center py-2">暂无完成记录</p>';
    } else {
        completions.forEach(completion => {
            const date = new Date(completion.completed_at);
            const formattedDate = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
            
            const item = document.createElement('div');
            item.className = 'flex justify-between items-center p-2 bg-gray-50 rounded';
            item.innerHTML = `
                <div class="flex items-center">
                    <i class="fas fa-check-circle text-green-500 mr-2"></i>
                    <span class="text-sm">${formattedDate}</span>
                </div>
            `;
            completionsList.appendChild(item);
        });
    }
    
    // 显示模态框
    document.getElementById('habitDetailsModal').classList.remove('hidden');
}

// 隐藏习惯详情模态框
function hideHabitDetailsModal() {
    document.getElementById('habitDetailsModal').classList.add('hidden');
    currentViewHabitId = null;
}

function getIconInfo(habit) {
    // 判断是否有存储的icon_data
    if (habit.trigger_data && habit.trigger_data.includes('icon:')) {
        const iconData = habit.trigger_data.split('|').find(part => part.startsWith('icon:'));
        const colorData = habit.trigger_data.split('|').find(part => part.startsWith('color:'));
        
        if (iconData && colorData) {
            return {
                icon: iconData.replace('icon:', ''),
                color: colorData.replace('color:', '')
            };
        }
    }
    
    // 默认图标和颜色
    const defaultIcons = {
        'time': { icon: 'clock', color: 'blue' },
        'location': { icon: 'map-marker-alt', color: 'red' },
        'activity': { icon: 'running', color: 'yellow' }
    };
    
    return defaultIcons[habit.trigger_type] || { icon: 'check', color: 'green' };
}

function getTriggerText(habit) {
    const type = habit.trigger_type;
    
    if (habit.trigger_data) {
        // 如果有数据，提取实际的触发数据（排除图标数据）
        const dataParts = habit.trigger_data.split('|').filter(part => 
            !part.startsWith('icon:') && !part.startsWith('color:')
        );
        
        if (dataParts.length > 0) {
            return dataParts[0];
        }
    }
    
    // 默认文本
    switch (type) {
        case 'time':
            return '每天固定时间';
        case 'location':
            return '特定位置时';
        case 'activity':
            return '特定活动后';
        default:
            return '自定义提醒';
    }
}

// 显示完成习惯的模态框
function showCompleteModal(habitId, habitTitle) {
    // 先检查是否已有完成模态框，避免重复创建
    const existingModal = document.getElementById('completeHabitModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    currentCompleteHabitId = habitId;
    
    // 创建完成习惯模态框
    const completeModal = document.createElement('div');
    completeModal.id = 'completeHabitModal';
    completeModal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-30';
    
    completeModal.innerHTML = `
        <div class="bg-white rounded-xl p-6 w-full max-w-md modal-content">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">完成习惯</h3>
                <button onclick="hideCompleteModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <p class="mb-6 text-gray-600">您将要完成"${habitTitle}"习惯，请选择完成类型：</p>
            <div class="flex space-x-4">
                <button onclick="completeHabit(${habitId}, false)" class="flex-1 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg">
                    <i class="fas fa-check mr-2"></i> 单次完成
                </button>
                <button onclick="completeHabit(${habitId}, true)" class="flex-1 bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg">
                    <i class="fas fa-check-double mr-2"></i> 彻底完成
                </button>
            </div>
            <p class="text-xs text-gray-500 mt-2">
                <b>单次完成</b>：记录今天完成情况，习惯仍会显示在列表中。<br>
                <b>彻底完成</b>：完全掌握此习惯，将归档并不再显示在待完成列表中。
            </p>
        </div>
    `;
    
    document.body.appendChild(completeModal);
    
    // 点击模态框外部关闭
    completeModal.addEventListener('click', function(e) {
        if (!e.target.closest('.modal-content') && e.target === this) {
            hideCompleteModal();
        }
    });
}

// 完成习惯
async function completeHabit(habitId, isCompleted = false) {
    try {
        hideCompleteModal();
        
        const response = await fetch(`/api/habits/${habitId}/complete`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ is_completed: isCompleted })
        });
        
        if (response.ok) {
            const data = await response.json();
            
            // 更新数据
            loadUserData();
            
            // 显示成功消息
            if (isCompleted) {
                showToast('习惯已彻底完成', '恭喜你已完全掌握这个习惯！');
            } else {
                showToast('习惯已完成', '真棒！继续保持！');
            }
            
            // 如果动机分数增加，显示额外消息
            if (data.motivation_score > 0) {
                setTimeout(() => {
                    showToast('动机提升', `你获得了 +${data.motivation_score} 动机分数！`);
                }, 1500);
            }
        } else {
            const error = await response.json();
            showToast('操作失败', error.error || '完成习惯失败');
        }
    } catch (error) {
        console.error('完成习惯错误:', error);
        showToast('操作失败', '服务器错误，请稍后重试');
    }
}

// 显示通知提示
function showToast(title, message) {
    const toast = document.getElementById('completionToast');
    
    // 设置内容
    toast.querySelector('h4').textContent = title || '习惯已完成！';
    toast.querySelector('p').textContent = message || '坚持下去，好习惯正在形成。';
    
    // 显示并动画
    toast.style.opacity = '1';
    toast.style.transform = 'translateX(0)';
    
    // 设置自动隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(20px)';
    }, 3000);
}

// 添加习惯模态框
function showAddHabitModal() {
    document.getElementById('addHabitModal').classList.remove('hidden');
    updateTriggerFields(); // 确保正确显示触发字段
}

function hideAddHabitModal() {
    document.getElementById('addHabitModal').classList.add('hidden');
}

// 图标选择
function setupIconButtons() {
    const iconButtons = document.querySelectorAll('.icon-btn');
    
    iconButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有按钮的选中状态
            iconButtons.forEach(btn => {
                btn.classList.remove('bg-blue-50', 'border-blue-300', 'icon-selected');
            });
            
            // 添加当前按钮的选中状态
            this.classList.add('bg-blue-50', 'border-blue-300', 'icon-selected');
            
            // 更新选中的图标和颜色值
            document.getElementById('selectedIcon').value = this.dataset.icon;
            document.getElementById('selectedColor').value = this.dataset.color;
        });
    });
}

// 触发方式字段切换
function updateTriggerFields() {
    const triggerType = document.getElementById('habitTrigger').value;
    const timeFields = document.getElementById('timeTriggerFields');
    const locationFields = document.getElementById('locationTriggerFields');
    const activityFields = document.getElementById('activityTriggerFields');
    
    // 隐藏所有字段
    timeFields.classList.add('hidden');
    locationFields.classList.add('hidden');
    activityFields.classList.add('hidden');
    
    // 显示选中类型的字段
    if (triggerType === 'time') {
        timeFields.classList.remove('hidden');
    } else if (triggerType === 'location') {
        locationFields.classList.remove('hidden');
    } else if (triggerType === 'activity') {
        activityFields.classList.remove('hidden');
    }
}

document.getElementById('addHabitForm').addEventListener('submit', async (e) => {
    e.preventDefault();

    const title = document.getElementById('habitName').value.trim();
    const difficulty = document.getElementById('habitDifficulty').value;
    const triggerType = document.getElementById('habitTrigger').value;
    const selectedIcon = document.getElementById('selectedIcon').value;
    const selectedColor = document.getElementById('selectedColor').value;
    
    // 验证习惯名称是否填写
    if (!title) {
        alert('习惯名称不能为空');
        return;
    }
    
    // 检查习惯名称是否已经存在
    try {
        const checkResponse = await fetch('/api/habits/check-title', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ title })
        });
        
        const checkResult = await checkResponse.json();
        
        if (checkResult.exists) {
            alert('该习惯名称已存在，请使用其他名称');
            return;
        }
        
        // 获取相应触发类型的数据
        let triggerData = '';
        if (triggerType === 'time') {
            const time = document.getElementById('habitTime').value;
            triggerData = `每天 ${time}|icon:${selectedIcon}|color:${selectedColor}`;
        } else if (triggerType === 'location') {
            const location = document.getElementById('habitLocation').value;
            triggerData = `${location}|icon:${selectedIcon}|color:${selectedColor}`;
        } else if (triggerType === 'activity') {
            const activity = document.getElementById('habitActivity').value;
            triggerData = `${activity}|icon:${selectedIcon}|color:${selectedColor}`;
        }

        const response = await fetch('/api/habits', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                title, 
                difficulty, 
                trigger_type: triggerType,
                trigger_data: triggerData
            })
        });

        if (response.ok) {
            hideAddHabitModal();
            showToast('习惯已添加！', '从现在开始，一步步培养好习惯吧！');
            loadUserData();
            
            // 重置表单
            document.getElementById('habitName').value = '';
        }
    } catch (error) {
        console.error('添加习惯错误:', error);
    }
});

// 统计和图表
function updateStats(stats) {
    document.getElementById('totalHabits').textContent = stats.total_habits;
    document.getElementById('motivationScore').textContent = stats.motivation_score;
    document.getElementById('streakCount').textContent = stats.streak_count;
    document.getElementById('monthlyCompletions').textContent = stats.monthly_completions;
    
    // 更新动机水平
    updateMotivationDisplay(stats.motivation_score);
}

function updateMotivationDisplay(score) {
    const level = document.getElementById('motivationLevel');
    const bar = document.getElementById('motivationBar');
    const message = document.getElementById('motivationMessage');
    
    level.textContent = `${score}/100`;
    bar.style.width = `${score}%`;
    
    // 更新颜色
    bar.className = 'h-2.5 rounded-full';
    if (score < 30) {
        bar.classList.add('bg-red-500');
        message.textContent = '动机水平较低，从小习惯开始，不要给自己太大压力。';
    } else if (score < 60) {
        bar.classList.add('bg-yellow-500');
        message.textContent = '动机处于中等水平，坚持完成习惯会让动力持续提升！';
    } else {
        bar.classList.add('bg-green-500');
        message.textContent = '你的动机水平良好！继续保持这些小习惯会更容易。';
    }
}

function renderBadges(badges) {
    const container = document.getElementById('badgesContainer');
    container.innerHTML = '';
    
    if (!badges || badges.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center col-span-3 py-3">继续完成习惯来获取成就徽章！</p>';
        return;
    }
    
    badges.forEach(badge => {
        const badgeEl = document.createElement('div');
        badgeEl.className = 'flex flex-col items-center badge-animation';
        badgeEl.innerHTML = `
            <div class="h-12 w-12 rounded-full bg-${badge.color}-100 flex items-center justify-center mb-1">
                <i class="fas fa-${badge.icon} text-${badge.color}-500"></i>
            </div>
            <span class="text-xs text-center">${badge.name}</span>
        `;
        container.appendChild(badgeEl);
    });
}

// 初始化图表
function initProgressChart(chartData) {
    const ctx = document.getElementById('progressChart').getContext('2d');
    
    if (progressChart) {
        progressChart.destroy();
    }
    
    // 确保当前月份的动机分数与顶部显示的一致
    if (chartData.motivation_data && chartData.motivation_data.length > 0) {
        const currentMonthIndex = chartData.motivation_data.length - 1;
        const currentMotivationScore = parseInt(document.getElementById('motivationScore').textContent);
        if (currentMotivationScore) {
            chartData.motivation_data[currentMonthIndex] = currentMotivationScore;
        }
    }

    progressChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartData.labels,
            datasets: [
                {
                    label: '习惯完成率',
                    data: chartData.completion_data,
                    borderColor: '#10B981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    tension: 0.3,
                    fill: true
                },
                {
                    label: '动机分数',
                    data: chartData.motivation_data,
                    borderColor: '#3B82F6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.3,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });
}

// 动机评估
function assessMotivation() {
    // 刷新统计数据并更新动机评估
    loadUserData();
}

// 显示删除确认对话框
function showDeleteConfirm(habitId, habitTitle) {
    if (confirm(`确定要删除习惯"${habitTitle}"吗？这将永久删除该习惯及其所有完成记录。`)) {
        deleteHabit(habitId);
    }
}

// 删除习惯
async function deleteHabit(habitId) {
    try {
        const response = await fetch(`/api/habits/${habitId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });

        if (response.ok) {
            // 从UI中移除
            const habitCard = document.querySelector(`.habit-card[data-habit-id="${habitId}"]`);
            if (habitCard) {
                habitCard.remove();
            }
            
            // 如果没有习惯了，显示空提示
            const container = document.getElementById('habitsContainer');
            if (container.children.length === 0) {
                container.innerHTML = '<p class="text-gray-500 text-center py-8">你还没有添加任何习惯，点击上方的"添加习惯"按钮开始吧！</p>';
            }
            
            // 刷新统计数据
            loadUserData();
            showToast('习惯已删除', '你可以随时添加新的习惯。');
        }
    } catch (error) {
        console.error('删除习惯错误:', error);
    }
}

// 用户中心功能
function showUserCenter() {
    // 先检查是否已有用户中心弹窗，避免重复创建
    const existingModal = document.getElementById('userCenterModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 创建用户中心模态框
    const userCenterModal = document.createElement('div');
    userCenterModal.id = 'userCenterModal';
    userCenterModal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-30';
    
    userCenterModal.innerHTML = `
        <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold">用户中心</h3>
                <button id="closeUserCenterBtn" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="mb-6">
                <div class="flex items-center mb-4">
                    <div class="h-16 w-16 rounded-full bg-green-100 flex items-center justify-center mr-4">
                        <span class="text-green-600 text-2xl font-medium">${userEmail.charAt(0).toUpperCase()}</span>
                    </div>
                    <div>
                        <h4 class="text-lg font-medium">${userEmail}</h4>
                        <p class="text-sm text-gray-500" id="userJoinDate">加入日期：加载中...</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-3 gap-4 mb-6">
                    <div class="bg-blue-50 rounded-lg p-3 text-center">
                        <p class="text-sm text-blue-600 mb-1">习惯总数</p>
                        <p class="text-xl font-bold text-blue-800" id="ucTotalHabits">0</p>
                    </div>
                    <div class="bg-green-50 rounded-lg p-3 text-center">
                        <p class="text-sm text-green-600 mb-1">已彻底完成</p>
                        <p class="text-xl font-bold text-green-800" id="ucArchivedHabits">0</p>
                    </div>
                    <div class="bg-purple-50 rounded-lg p-3 text-center">
                        <p class="text-sm text-purple-600 mb-1">总完成次数</p>
                        <p class="text-xl font-bold text-purple-800" id="ucTotalCompletions">0</p>
                    </div>
                </div>
            </div>
            
            <div class="border-t border-gray-200 pt-4 mb-6">
                <h4 class="font-medium text-gray-800 mb-3">账户设置</h4>
                
                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <h5 class="font-medium mb-3">修改密码</h5>
                    <form id="changePasswordForm" class="space-y-3">
                        <div>
                            <label class="block text-sm text-gray-700 mb-1">当前密码</label>
                            <input type="password" id="currentPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-700 mb-1">新密码</label>
                            <input type="password" id="newPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-700 mb-1">确认新密码</label>
                            <input type="password" id="confirmPassword" class="w-full px-3 py-2 border border-gray-300 rounded-lg" required>
                        </div>
                        <div class="pt-2">
                            <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-lg text-sm">修改密码</button>
                        </div>
                    </form>
                </div>
                
                <div id="adminPanelEntry" class="bg-gray-50 rounded-lg p-4 hidden">
                    <h5 class="font-medium mb-3">管理员功能</h5>
                    <button id="enterAdminBtn" class="bg-indigo-500 text-white px-4 py-2 rounded-lg text-sm">
                        进入管理后台
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(userCenterModal);
    
    // 获取用户信息
    fetchUserInfo();
    
    // 设置修改密码表单提交事件
    document.getElementById('changePasswordForm').addEventListener('submit', function(e) {
        e.preventDefault();
        changePassword();
    });
    
    // 使用onclick而不是addEventListener
    document.getElementById('closeUserCenterBtn').onclick = function() {
        hideUserCenter();
    };
    
    // 检查管理员权限
    checkAdminAccess();
}

function hideUserCenter() {
    const modal = document.getElementById('userCenterModal');
    if (modal) {
        modal.remove();
    }
}

async function fetchUserInfo() {
    try {
        const response = await fetch('/api/habits/user-info', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const userData = await response.json();
            
            // 更新用户中心信息
            const joinDate = new Date(userData.created_at);
            document.getElementById('userJoinDate').textContent = `加入日期：${joinDate.toLocaleDateString()}`;
            document.getElementById('ucTotalHabits').textContent = userData.total_habits || 0;
            document.getElementById('ucArchivedHabits').textContent = userData.archived_habits || 0;
            document.getElementById('ucTotalCompletions').textContent = userData.total_completions || 0;
        }
    } catch (error) {
        console.error('获取用户信息错误:', error);
    }
}

// 检查是否有管理员权限
async function checkAdminAccess() {
    try {
        const { response, data, error } = await fetchWithAuth('/api/admin/check-access');
        
        if (error) {
            console.error(error);
            return;
        }
        
        if (response && response.ok && data.hasAccess) {
            // 显示管理员入口
            document.getElementById('adminPanelEntry').classList.remove('hidden');
            
            // 添加进入管理后台按钮事件
            document.getElementById('enterAdminBtn').addEventListener('click', function() {
                // 使用带token的请求访问管理页面
                window.location.href = '/admin';
            });
        }
    } catch (error) {
        console.error('检查管理员权限错误:', error);
    }
}

async function changePassword() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    if (newPassword !== confirmPassword) {
        alert('两次输入的新密码不一致');
        return;
    }
    
    try {
        const response = await fetch('/api/habits/change-password', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ currentPassword, newPassword })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            alert('密码修改成功');
            hideUserCenter();
        } else {
            alert(data.error || '密码修改失败');
        }
    } catch (error) {
        console.error('修改密码错误:', error);
        alert('修改密码失败，请稍后重试');
    }
}

// 文章相关功能
async function loadArticles(limit = 3) {
    try {
        const container = document.getElementById('articlesContainer');
        container.innerHTML = '<div class="text-center text-gray-500 py-2"><i class="fas fa-spinner fa-spin mr-2"></i> 加载文章中...</div>';
        
        const response = await fetch(`/api/articles?limit=${limit}`);
        
        if (response.ok) {
            const data = await response.json();
            renderArticles(data.articles, container);
        } else {
            container.innerHTML = '<p class="text-gray-500 text-center py-2">加载文章失败，请稍后再试</p>';
        }
    } catch (error) {
        console.error('加载文章错误:', error);
        const container = document.getElementById('articlesContainer');
        container.innerHTML = '<p class="text-gray-500 text-center py-2">加载文章失败，请稍后再试</p>';
    }
}

function renderArticles(articles, container) {
    container.innerHTML = '';
    
    if (!articles || articles.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-2">暂无文章</p>';
        return;
    }
    
    articles.forEach(article => {
        const card = document.createElement('div');
        card.className = 'article-card bg-white border border-gray-200 hover:border-blue-300 rounded-lg p-4 transition-all cursor-pointer';
        card.onclick = () => viewArticleDetail(article.id);
        
        // 格式化日期
        const updatedDate = new Date(article.updated_at).toLocaleDateString();
        
        // 检查是否为置顶文章
        const pinnedBadge = article.is_pinned ? 
            '<span class="bg-red-100 text-red-600 text-xs px-2 py-1 rounded ml-2">置顶</span>' : '';
        
        card.innerHTML = `
            <h3 class="font-medium text-lg mb-2 flex items-center">
                ${article.title} ${pinnedBadge}
            </h3>
            <p class="text-gray-600 text-sm mb-3">${article.summary}</p>
            <div class="flex justify-between items-center text-xs text-gray-500">
                <span>${updatedDate}</span>
                <span>阅读全文 <i class="fas fa-chevron-right ml-1"></i></span>
            </div>
        `;
        
        container.appendChild(card);
    });
}

async function viewArticleDetail(articleId) {
    try {
        // 显示加载状态
        document.getElementById('articleTitle').textContent = '加载中...';
        document.getElementById('articleMeta').textContent = '';
        document.getElementById('articleContent').innerHTML = '<div class="flex justify-center py-8"><i class="fas fa-spinner fa-spin text-2xl text-gray-400"></i></div>';
        document.getElementById('articleDetailModal').classList.remove('hidden');
        
        const response = await fetch(`/api/articles/${articleId}`);
        
        if (response.ok) {
            const article = await response.json();
            
            // 设置标题和元信息
            document.getElementById('articleTitle').textContent = article.title;
            
            // 格式化日期
            const updatedDate = new Date(article.updated_at).toLocaleDateString();
            document.getElementById('articleMeta').textContent = `更新于: ${updatedDate}`;
            
            // 处理Markdown内容
            const markdownContent = article.content;
            
            // 使用简单的Markdown转换实现
            let htmlContent = convertMarkdown(markdownContent);
            
            document.getElementById('articleContent').innerHTML = htmlContent;
        } else {
            document.getElementById('articleContent').innerHTML = '<p class="text-center text-red-500">加载文章失败，请稍后再试</p>';
        }
    } catch (error) {
        console.error('查看文章详情错误:', error);
        document.getElementById('articleContent').innerHTML = '<p class="text-center text-red-500">加载文章失败，请稍后再试</p>';
    }
}

function hideArticleDetailModal() {
    document.getElementById('articleDetailModal').classList.add('hidden');
}

// 简单的Markdown转HTML函数（支持基本格式）
function convertMarkdown(text) {
    // 处理标题
    text = text.replace(/^# (.*$)/gm, '<h1 class="text-2xl font-bold my-4">$1</h1>');
    text = text.replace(/^## (.*$)/gm, '<h2 class="text-xl font-bold my-3">$1</h2>');
    text = text.replace(/^### (.*$)/gm, '<h3 class="text-lg font-bold my-2">$1</h3>');
    
    // 处理粗体
    text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    
    // 处理斜体
    text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
    
    // 处理列表
    text = text.replace(/^\- (.*$)/gm, '<li class="ml-4">$1</li>');
    
    // 将连续的<li>包装在<ul>中
    text = text.replace(/(<li.*?<\/li>\n)+/g, function(match) {
        return '<ul class="list-disc my-2 ml-5">' + match + '</ul>';
    });
    
    // 处理段落
    text = text.replace(/^(?!<[a-z])(.*$)/gm, function(match) {
        if (match.trim() === '') return '';
        return '<p class="my-2">' + match + '</p>';
    });
    
    // 处理换行
    text = text.replace(/\n/g, '');
    
    return text;
}

// 显示所有文章列表
async function showAllArticles(page = 1) {
    document.getElementById('allArticlesModal').classList.remove('hidden');
    await loadAllArticles(page);
}

async function loadAllArticles(page = 1, limit = 5) {
    try {
        const container = document.getElementById('allArticlesContainer');
        container.innerHTML = '<div class="text-center text-gray-500 py-4"><i class="fas fa-spinner fa-spin mr-2"></i> 加载文章中...</div>';
        
        const response = await fetch(`/api/articles?offset=${(page-1)*limit}&limit=${limit}`);
        
        if (response.ok) {
            const data = await response.json();
            renderAllArticles(data.articles, container);
            renderArticlesPagination(data.pagination, page);
        } else {
            container.innerHTML = '<p class="text-gray-500 text-center py-4">加载文章失败，请稍后再试</p>';
        }
    } catch (error) {
        console.error('加载所有文章错误:', error);
        const container = document.getElementById('allArticlesContainer');
        container.innerHTML = '<p class="text-gray-500 text-center py-4">加载文章失败，请稍后再试</p>';
    }
}

function renderAllArticles(articles, container) {
    container.innerHTML = '';
    
    if (!articles || articles.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-4">暂无文章</p>';
        return;
    }
    
    articles.forEach(article => {
        const card = document.createElement('div');
        card.className = 'article-card bg-white border border-gray-200 hover:border-blue-300 rounded-lg p-4 mb-4 transition-all cursor-pointer';
        card.onclick = () => {
            hideAllArticlesModal();
            viewArticleDetail(article.id);
        };
        
        // 格式化日期
        const updatedDate = new Date(article.updated_at).toLocaleDateString();
        
        // 检查是否为置顶文章
        const pinnedBadge = article.is_pinned ? 
            '<span class="bg-red-100 text-red-600 text-xs px-2 py-1 rounded ml-2">置顶</span>' : '';
        
        card.innerHTML = `
            <h3 class="font-medium text-lg mb-2 flex items-center">
                ${article.title} ${pinnedBadge}
            </h3>
            <p class="text-gray-600 text-sm mb-3">${article.summary}</p>
            <div class="flex justify-between items-center text-xs text-gray-500">
                <span>${updatedDate}</span>
                <span>阅读全文 <i class="fas fa-chevron-right ml-1"></i></span>
            </div>
        `;
        
        container.appendChild(card);
    });
}

function renderArticlesPagination(pagination, currentPage) {
    const paginationContainer = document.getElementById('articlesPagination');
    paginationContainer.innerHTML = '';
    
    const totalPages = Math.ceil(pagination.total / pagination.limit);
    
    if (totalPages <= 1) {
        return;
    }
    
    // 上一页按钮
    const prevButton = document.createElement('button');
    prevButton.className = `px-3 py-1 rounded ${currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'}`;
    prevButton.innerHTML = '<i class="fas fa-chevron-left"></i>';
    if (currentPage > 1) {
        prevButton.onclick = () => loadAllArticles(currentPage - 1, pagination.limit);
    }
    paginationContainer.appendChild(prevButton);
    
    // 页码按钮
    const maxPageButtons = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxPageButtons / 2));
    let endPage = Math.min(totalPages, startPage + maxPageButtons - 1);
    
    if (endPage - startPage + 1 < maxPageButtons) {
        startPage = Math.max(1, endPage - maxPageButtons + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const pageButton = document.createElement('button');
        pageButton.className = `px-3 py-1 rounded ${i === currentPage ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`;
        pageButton.textContent = i;
        pageButton.onclick = () => loadAllArticles(i, pagination.limit);
        paginationContainer.appendChild(pageButton);
    }
    
    // 下一页按钮
    const nextButton = document.createElement('button');
    nextButton.className = `px-3 py-1 rounded ${currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'}`;
    nextButton.innerHTML = '<i class="fas fa-chevron-right"></i>';
    if (currentPage < totalPages) {
        nextButton.onclick = () => loadAllArticles(currentPage + 1, pagination.limit);
    }
    paginationContainer.appendChild(nextButton);
}

function hideAllArticlesModal() {
    document.getElementById('allArticlesModal').classList.add('hidden');
}

function hideCompleteModal() {
    const modal = document.getElementById('completeHabitModal');
    if (modal) {
        modal.remove();
    }
    currentCompleteHabitId = null;
}

// 加载已完成习惯的函数
async function loadCompletedHabits(page = 1, pageSize = 5) {
    try {
        const container = document.getElementById('completedHabitsContainer');
        container.innerHTML = '<div class="text-center text-gray-500 py-4"><i class="fas fa-spinner fa-spin mr-2"></i> 加载已完成习惯...</div>';
        
        // 从服务器加载已彻底完成的习惯
        const { response, data, error } = await fetchWithAuth(`/api/habits/mastered?page=${page}&pageSize=${pageSize}`);
        
        if (error) {
            container.innerHTML = `<p class="text-gray-500 text-center py-4">${error}</p>`;
            return;
        }
        
        if (response && response.ok) {
            renderCompletedHabits(data.habits, data.pagination);
        } else {
            container.innerHTML = '<p class="text-gray-500 text-center py-4">加载已完成习惯失败，请稍后再试</p>';
        }
    } catch (error) {
        console.error('加载已完成习惯错误:', error);
        const container = document.getElementById('completedHabitsContainer');
        container.innerHTML = '<p class="text-gray-500 text-center py-4">加载已完成习惯失败，请稍后再试</p>';
    }
}

// 渲染已完成习惯
function renderCompletedHabits(habits, pagination) {
    const container = document.getElementById('completedHabitsContainer');
    container.innerHTML = '';
    
    if (!habits || habits.length === 0) {
        container.innerHTML = '<p class="text-gray-500 text-center py-4">您还没有彻底完成的习惯</p>';
        return;
    }
    
    habits.forEach(habit => {
        // 获取图标和颜色
        const iconInfo = getIconInfo(habit);
        
        // 将YYYY-MM-DD格式化为更友好的日期显示
        let completedDateText = '完成日期未知';
        if (habit.last_completed_at) {
            const completedDate = new Date(habit.last_completed_at);
            completedDateText = `彻底完成于 ${completedDate.toLocaleDateString()}`;
        }
        
        const card = document.createElement('div');
        card.className = 'habit-card bg-white border border-gray-200 rounded-lg p-4 transition-all duration-300';
        card.innerHTML = `
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                    <div class="h-10 w-10 rounded-full bg-${iconInfo.color}-100 flex items-center justify-center">
                        <i class="fas fa-${iconInfo.icon} text-${iconInfo.color}-500"></i>
                    </div>
                    <div>
                        <h3 class="font-medium">${habit.title}</h3>
                        <p class="text-xs text-gray-500">${completedDateText}</p>
                    </div>
                </div>
                <span class="text-green-600 text-sm">
                    <i class="fas fa-trophy mr-1"></i> 已彻底养成
                </span>
            </div>
        `;
        container.appendChild(card);
    });
    
    // 添加分页控件
    if (pagination && pagination.totalPages > 1) {
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'mt-6 flex items-center justify-between text-sm text-gray-500';
        
        const currentPage = pagination.page;
        const totalPages = pagination.totalPages;
        const total = pagination.total;
        
        const pageStart = ((currentPage - 1) * pagination.pageSize) + 1;
        const pageEnd = Math.min(currentPage * pagination.pageSize, total);
        
        paginationDiv.innerHTML = `
            <div>
                显示 ${pageStart}-${pageEnd} 条，共 ${total} 条
            </div>
            <div class="flex space-x-2">
                <button id="prevCompletedPageBtn" class="bg-gray-100 px-3 py-1 rounded-lg hover:bg-gray-200 ${currentPage <= 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <span class="px-2 py-1">第 ${currentPage} 页</span>
                <button id="nextCompletedPageBtn" class="bg-gray-100 px-3 py-1 rounded-lg hover:bg-gray-200 ${currentPage >= totalPages ? 'opacity-50 cursor-not-allowed' : ''}">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        `;
        
        container.appendChild(paginationDiv);
        
        // 添加分页按钮事件
        setTimeout(() => {
            const prevBtn = document.getElementById('prevCompletedPageBtn');
            const nextBtn = document.getElementById('nextCompletedPageBtn');
            
            if (prevBtn && currentPage > 1) {
                prevBtn.addEventListener('click', () => loadCompletedHabits(currentPage - 1));
            }
            
            if (nextBtn && currentPage < totalPages) {
                nextBtn.addEventListener('click', () => loadCompletedHabits(currentPage + 1));
            }
        }, 0);
    }
}

// 获取验证码
async function getVerificationCode(email) {
    try {
        const response = await fetch('/api/auth/captcha', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        });
        
        if (response.ok) {
            // 更新验证码图片
            const captchaImage = document.getElementById('captchaImage');
            if (captchaImage) {
                // 添加时间戳参数以避免缓存
                captchaImage.src = `/api/auth/captcha?t=${new Date().getTime()}`;
            }
        }
    } catch (error) {
        console.error('获取验证码错误:', error);
    }
} 